import React, { Component } from 'react'
import { Breadcrumb } from 'antd'
import { withRouter } from 'react-router-dom'

/**
 * 面包屑要显示内容跟路由关联关系
 */
const breadcrumbMap = {
  '/home': '首页',
  '/home/user': '用户管理',
  // '/home/role': '角色管理',
  '/home/shop': '店铺管理',
  '/home/product': '产品管理',
  '/home/product/list': '产品列表',
  '/home/product/category': '产品分类',
  '/home/product/list/add': '添加产品',
  '/home/product/list/detail': '商品详情',
}
let UNLISTNE
class MyBreadcrumb extends Component {
  state = {
    breadcrumbArray: [],
  }
  getPath = () => {
    // /home/product/list/add
    // (1)通过路由对象获取路由地址，拆分为数组
    const pathArray = this.props.history.location.pathname
      .split('/')
      .filter((item) => item)
    console.log(pathArray)
    // console.log(this.props.history)
    // (2)
    const breadcrumbArray = pathArray.map((_, index) => {
      let url = `/${pathArray.slice(0, index + 1).join('/')}`
      console.log(url)
      return (
        <Breadcrumb.Item key={breadcrumbMap[url]}>
          <a href={url}>{breadcrumbMap[url]}</a>
        </Breadcrumb.Item>
      )
    })
    this.setState({
      breadcrumbArray,
    })
  }
  componentDidMount() {
    this.getPath()
    // 检测到路由路径发生变化，执行一次getPath
    UNLISTNE = this.props.history.listen(() => {
      this.getPath()
    })
  }
  // 为了防止内存泄漏，我们需要在组件销毁的时候，清除路由的监听器
  componentWillUnmount() {
    // odiv.onclick = function(){}  odiv.onclick = null
    // odiv.addEventListener("click",function(){},false)
    // odv.removeEventListener("click",function(){})
    // 判断UNLISTNE是否为空，如果不为空，调用UNLISTNE()解除绑定
    UNLISTNE && UNLISTNE()
  }
  render() {
    return (
      <Breadcrumb style={{ margin: '16px 0' }}>
        {this.state.breadcrumbArray}
      </Breadcrumb>
    )
  }
}

export default withRouter(MyBreadcrumb)
